import { Bigwheel } from '../../../module/bigwheel.js'
const Api = new Bigwheel()
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    hash: '',
    share_from: '',
    mobile: '',
    play_num: 0, //抽奖次数
    prize_list: [], //奖品列表
    content: '',
    slicePrizes: [],
    img_url: '',
    bg_url: '',
    pan_bg:'',
    pan_point:'',
    my_prize: false,
    start_rotating_degree: 0, //初始旋转角度
    rotate_angle: 0, //将要旋转的角度
    start_rotating_degree_pointer: 0, //指针初始旋转角度
    rotate_angle_pointer: 0, //指针将要旋转的度数
    rotate_transition: "transform 6s ease-in-out", //初始化选中的过度属性控制
    rotate_transition_pointer: "transform 12s ease-in-out", //初始化指针过度属性控制
    click_flag: true, //是否可以旋转抽奖
    i: 0, //测试使用
    modal: true,
    hide_canvas: false,
    modal_title: '很抱歉',
    prize_name: '您没有中奖',
    big_text: '领取成功',
    amount: '',
    tips1: '',
    tips2: '',
    share_title: '',
    share_url: '',
    user: {},
    prize_data: {},
    ids: []
  },

  getPhone: function(e) {
    var that = this;
    Api.mobile(e.detail).then((data) => {
      that.setData({ mobile: data.user.mobile });
      that.rotate_handle();
    })
  },

  rotate_handle: function () {
    var that = this;
    if (!that.data.click_flag) return false;
    // 判断状态
    var item_info = that.data.item_info;
    var user = that.data.user;
    if (item_info.status == 2) {
      wx.showToast({ title: '活动尚未开始',icon: 'none' })
      return;
    }
    if (item_info.status == 3) {
      wx.showToast({ title: '活动已经结束',icon: 'none' })
      return;
    }
    if (item_info.status != 1) {
      wx.showToast({ title: '活动暂停中',icon: 'none' })
      return;
    }
    // 判断是否拥有抽奖次数
    var limit_desc = item_info.limit_desc ? item_info.limit_desc : '抽奖次数已用完';
    if (user.total_num <= user.used_num) {
      app.toast(limit_desc);
      return;
    }

    // 本地减少一次游戏次数
    var remain_num = that.data.play_num - 1;
    if (remain_num < 0) {
      remain_num = 0;
    }
    // 
    user.used_num = user.used_num + 1;
    that.setData({
      play_num: remain_num,
      user: user
    });
    
    Api.award({
      id: that.data.item_info.id,
      ids: that.data.ids,
      loading: false
    }).then((data) => {
      if (data.state) {
        // 返回的是奖品的id
        var i = 0;
        that.data.prize_list.forEach(function (value, index) {
          if (value.id == data.data.prize_id) {
            i = index;
          }
        });
        that.rotating(i);
        that.setData({
          i: i,
          prize_data: data.data
        });
      } else {
        app.toast(data.message);
      }
    }).catch((err) => {
      wx.showToast({ title: err,icon: 'none' })
    })
  },

  rotating: function(index) {
    var type = 0; // 默认为 0  转盘转动 1 箭头和转盘都转动(暂且遗留)
    var during_time = 5; // 默认为1s
    var result_index = index; // 最终要旋转到哪一块，对应prize_list的下标
    var result_angle = [337.5, 292.5, 247.5, 202.5, 157.5, 112.5, 67.5, 22.5]; //最终会旋转到下标的位置所需要的度数
    var rand_circle = 6; // 附加多转几圈，2-3
    this.setData({
      click_flag: false // 旋转结束前，不允许再次触发
    });
    if (type == 0) {
      // 转动盘子
      var rotate_angle = this.data.start_rotating_degree + rand_circle * 360 + result_angle[result_index] - this.data.start_rotating_degree % 360;
      this.setData({
        start_rotating_degree: rotate_angle,
        rotate_angle: "rotate(" + rotate_angle + "deg)"
      });
      this.start_rotating_degree = rotate_angle;
      this.rotate_angle = "rotate(" + rotate_angle + "deg)";

      var that = this;
      // 旋转结束后，允许再次触发
      setTimeout(function () {
        that.setData({
          click_flag: true
        });
        that.game_over(that.data.i);
      }, during_time * 1000 + 1500); // 延时，保证转盘转完
    } else {
      //
    }
  },

  game_over: function() {
    var that = this;
    var prize = this.data.prize_list[this.data.i];
    var modal_title = '很抱歉';
    var prize_name = '您没有中奖';
    var big_text = '领取成功';
    var tips1 = '';
    var tips2 = '';
    if (prize.type == 1 || prize.type == 4) { // 实物优惠券
      modal_title = '恭喜您';
      prize_name = '获得' + prize.title;
      big_text = '领取成功';
      tips1 = '请在中奖记录中进行领取';
    } else if (prize.type == 2) { // 红包
      modal_title = '恭喜您';
      prize_name = '获得现金红包';
      big_text = that.data.prize_data.amount;
      tips1 = '已发放至零钱';
    } else if (prize.type == 3) { // 积分
      modal_title = '恭喜您';
      prize_name = '获得系统积分';
      big_text = parseInt(prize.credit);
      tips1 = '已发放至用户中心';
    } else if (prize.type == 5) { // 再来一次
      modal_title = '恭喜您';
      prize_name = '获得抽奖机会';
      big_text = '再来' + parseInt(prize.play_num) + '次';
      // 增加剩余次数
      var user = that.data.user;
      user.total_num += parseInt(prize.play_num);
      var remain_num = that.data.play_num + parseInt(prize.play_num);
      that.setData({
        user: user,
        play_num: remain_num
      });
      tips1 = '赶紧再来一次吧！';
    } else if (prize.type == 6) { // 平台优惠券
      modal_title = '恭喜您';
      prize_name = '获得平台优惠券';
      big_text = prize.title;
      tips1 = '已发放至卡包！';
    } else {
      modal_title = '很抱歉';
      prize_name = '您没有中奖';
      big_text = 'SORRY';
      tips1 = '赶紧再来一次吧！';
    }
    that.setData({
      hide_canvas: true,
      modal_title: modal_title,
      prize_name: prize_name,
      big_text: big_text,
      tips1: tips1,
      modal: false
    })
  },
  //关闭弹窗
  close_toast: function() {
    this.setData({
      modal: true
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id ? options.id : '';
    var hash = options.hash ? options.hash : '';
    var share_from = options.share_from;
    this.setData({
      id: id,
      hash: hash ? hash : '',
      share_from: share_from ? share_from : ''
    });
  },

  getBigWheel: function (id, hash, share_from, cb) {
    var that = this;
    Api.index({
      id: id,
      hash: hash,
      share_from: share_from
    }).then((data) => {
      wx.setNavigationBarTitle({
        title: data.title
      });
      var play_num = data.user.total_num - data.user.used_num;
      
      that.setData({
        item_info:data,
        user: data.user,
        share_title: data.share_title ? data.share_title : data.title,
        share_url: data.share_url,
        my_prize: data.my_prize == 1 ? true : false,
        bg_url: data.bg ? data.bg : '',
        pan_bg: data.pan_bg ? data.pan_bg : '',
        pan_point: data.pan_point ? data.pan_point : '',
        slicePrizes: data.prizes,
        play_num: play_num >= 0 ? play_num : 0,
        content: data.content,
        copyright:data.copyright,
        mobile: data.mobile
      });
      
      var ids = [];
      data.prizes.forEach((item) => {
        ids.push(item.id);
      });
      // 格式化奖项 prize_list
      var prizeArr = data.prizes.filter(function(value){
        return value.id > 0;
      });
      var freeArr = data.prizes.filter(function (value) {
        return value.id == 0;
      });
      freeArr = freeArr[0];
      let evenArr = new Array(8); //创建一个数组，方便操作。
      let j = 0;
      for (let i = 0; i < 8; i++) {
        if (j > data.prizes.length - 1) {
          j = 0;
        }
        evenArr[i] = data.prizes[j];
        j++;
      }
      that.setData({
        ids: ids,
        prize_list: evenArr
      });

      if (data.per_share == 0) {
        wx.hideShareMenu();
      }
      typeof cb == "function" && cb(data);
    }).catch((err) => {
      app.toast(err);
      wx.showToast({ title:err, icon:'none' })
    })
  },

  showBigWheel: function () {
    var that = this;
    this.getBigWheel(this.data.id, this.data.hash, this.data.share_from, function (data) {
      var slicePrizes = data.prizes;
      var item_info = data;
      if (item_info.hash_expired == 1) {
        var expired_text = item_info.expired_text ? item_info.expired_text : '已超时';
        app.toast(expired_text);
      }
      if (item_info.hash_expired == 2) {
        app.toast('抽奖次数 +' + item_info.per_read, '../assets/gift.png');
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    that.showBigWheel();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: that.data.share_title,
      path: that.data.share_url
    }
  },

  linkTap: function (e) {
    let link = e.currentTarget.dataset.link;
    if (link) {
      wx.navigateTo({
        url: link
      })
    }
  },
})